package com.xuyuan.ai.deepseek;


import lombok.extern.slf4j.Slf4j;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.text.TextContentRenderer;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;


/**
 * @author xuyuan
 * @desc 初识Spring AI - 利用OpenAI模块对接Deepseek。也可以直接使用ChatClient调用Deepseek
 */
@Slf4j
@RestController
public class DeepSeekChatController {

    private OpenAiChatModel chatModel;

    private final ChatClient chatClient;

    public DeepSeekChatController(ChatClient.Builder chatClientBuilder, OpenAiChatModel chatModel) {
        this.chatClient = chatClientBuilder.build();
        this.chatModel = chatModel;
    }

    /**
     * 聊天接口
     *
     * @param message
     * @return
     */
    @GetMapping("/ds/chat")
    public String generate(@RequestParam(value = "message", defaultValue = "hello") String message) {
        try {
            String markdown = this.chatModel.call(message);
            Parser parser = Parser.builder().build();
            Node document = parser.parse(markdown);
            TextContentRenderer renderer = TextContentRenderer.builder().build();
            String text = renderer.render(document);
            System.out.println(text);
            return text;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 流式聊天接口
     *
     * @param message
     * @return
     */
    @GetMapping("/ds/chatStream")
    public Flux<String> generateStream(@RequestParam(value = "message", defaultValue = "hello") String message) {
        return this.chatClient.prompt()
                .user(message)
                .stream()
                .content();
    }

}